<?php
namespace frontend\controllers;

use Yii;
use yii\web\Controller;
use yii\data\Pagination;

/**
 * Hello controller
 */
class ServerController extends Controller
{
    public function init()
    {
        set_time_limit(0);
        parent::init();
    }
    
    
    public function actionIndex()
    {
        $log_file = './'.date('YmdH').'_index.txt';
        file_put_contents($log_file,"----------------index---------------\n",FILE_APPEND);
        
        $error = [];
        $ok = [];
        
        //$page
        $count = (new \yii\db\Query())->from('busy_admin_product')->count();
        $pagination = new Pagination(['totalCount' => $count]);
        $pagination->setPageSize(50);
        
        $rows = (new \yii\db\Query())
        ->select('*')
        ->from('busy_admin_product')
        ->offset($pagination->getOffset())
        ->limit($pagination->limit)
        ->orderBy('id asc')
        ->all();
        
       
        if (empty($rows)) {
            echo "data empty\n\r";
        }
        
        foreach ($rows as $k => $v) {
            
            if (empty($v['repayment_data'])) {
                continue;
            }
            
            $data = unserialize($v['repayment_data']);
            
            $serverA['server_rate'] = $data['server_rate'];
            $serverA['server_cycle'] = $data['server_cycle'];
            
            $checkA['platform']['platform_service'] = $data['platform_service'];
            $checkA['platform']['platform_cycle_rate'] = $data['platform_cycle_rate'];
            $checkA['platform']['platform_cycle'] = $data['platform_cycle'];
            
            $checkA['account']['account_service'] = $data['account_service'];
            $checkA['account']['account_cycle_rate'] = $data['account_cycle_rate'];
            $checkA['account']['account_cycle'] = $data['account_cycle'];
            
            $checkA['pay']['pay_service'] = $data['pay_service'];
            $checkA['pay']['pay_cycle_rate'] = $data['pay_cycle_rate'];
            $checkA['pay']['pay_cycle'] = $data['pay_cycle'];
            
            $res = $this->reverseCheck($serverA, $checkA);
            
            if (!$res) {
                $error[] = $v['id'];
                file_put_contents($log_file, $v['id']."\n",FILE_APPEND);
            } else {
                $ok[] =$v['id'];
            }
        }
        
        echo "<pre>";
        echo "ok<br/>";
        var_dump($ok);
        
        echo "<hr/>";
        
        echo "q<br/>";
        var_dump($error);

    }

    
    public function actionHello()
    {
        $error = [];
        $ok = [];
        
        $log_file = './'.date('YmdH').'_hello.txt';
        file_put_contents($log_file,"----------------hello---------------\n",FILE_APPEND);
        
        
        //$page
        $count = (new \yii\db\Query())->from('busy_admin_product')->count();
        $pagination = new Pagination(['totalCount' => $count]);
        $pagination->setPageSize(50);
        
        $rows = (new \yii\db\Query())
        ->select('*')
        ->from('busy_admin_product')
        ->offset($pagination->getOffset())
        ->limit($pagination->limit)
        ->orderBy('id asc')
        ->all();
        
        
        if (empty($rows)) {
            echo "data empty\n\r";
        }
        
        foreach ($rows as $k => $v) {
            
            if (empty($v['repayment_data'])) {
                continue;
            }
            
            $data = unserialize($v['repayment_data']);
            
            if ($data['platform_cycle'] == 0 && ($data['account_cycle'] != 0 || $data['pay_cycle'] != 0)) {
                $error[] = $v['id'];
                file_put_contents($log_file, $v['id']."\n",FILE_APPEND);
           } else {
               $ok[] =$v['id'];
           }
        }
        
        echo "<pre>";
        echo "ok<br/>";
        var_dump($ok);
        
        echo "<hr/>";
        
        echo "q<br/>";
        var_dump($error);
   
    }
    
    
    public function actionIndex2()
    {
        
        $error = [];
        $ok = [];
        
        $log_file = './'.date('YmdH').'_index2.txt';
        file_put_contents($log_file,"----------------index2-again---------------\n",FILE_APPEND);
        //$page
        $count = (new \yii\db\Query())->from('busy_admin_product')->count();
        $pagination = new Pagination(['totalCount' => $count]);
        $pagination->setPageSize(50);
        
        $rows = (new \yii\db\Query())
        ->select('*')
        ->from('busy_admin_product')
        ->offset($pagination->getOffset())
        ->limit($pagination->limit)
        ->orderBy('id asc')
        ->all();
        
        
        if (empty($rows)) {
            echo "data empty\n\r";
        }
        
        foreach ($rows as $k => $v) {
            
            if (empty($v['repayment_data'])) {
                continue;
            }
            
            $data = unserialize($v['repayment_data']);
            
            $serverA['server_rate'] = $data['again_server_rate'];
            $serverA['server_cycle'] = $data['again_server_cycle'];
            
            $checkA['platform']['platform_service'] = $data['again_platform_service'];
            $checkA['platform']['platform_cycle_rate'] = $data['again_platform_cycle_rate'];
            $checkA['platform']['platform_cycle'] = $data['again_platform_cycle'];
            
            $checkA['account']['account_service'] = $data['again_account_service'];
            $checkA['account']['account_cycle_rate'] = $data['again_account_cycle_rate'];
            $checkA['account']['account_cycle'] = $data['again_account_cycle'];
            
            $checkA['pay']['pay_service'] = $data['again_pay_service'];
            $checkA['pay']['pay_cycle_rate'] = $data['again_pay_cycle_rate'];
            $checkA['pay']['pay_cycle'] = $data['again_pay_cycle'];
            
            $res = $this->reverseCheck($serverA, $checkA);
            
            if (!$res) {
                $error[] = $v['id'];
                file_put_contents($log_file, $v['id']."\n",FILE_APPEND);
            } else {
                $ok[] =$v['id'];
            }
        }
        
        echo "<pre>";
        echo "ok<br/>";
        var_dump($ok);
        
        echo "<hr/>";
        
        echo "q<br/>";
        var_dump($error);
        
    }
    
    
    
    public function actionHello2()
    {
        $error = [];
        $ok = [];
        
        $log_file = './'.date('YmdH').'_hello2.txt';
        file_put_contents($log_file,"----------------hello2-again---------------\n",FILE_APPEND);
        
        //$page
        $count = (new \yii\db\Query())->from('busy_admin_product')->count();
        $pagination = new Pagination(['totalCount' => $count]);
        $pagination->setPageSize(50);
        
        $rows = (new \yii\db\Query())
        ->select('*')
        ->from('busy_admin_product')
        ->offset($pagination->getOffset())
        ->limit($pagination->limit)
        ->orderBy('id asc')
        ->all();
        
        
        if (empty($rows)) {
            echo "data empty\n\r";
        }
        
        foreach ($rows as $k => $v) {
            
            if (empty($v['repayment_data'])) {
                continue;
            }
            
            $data = unserialize($v['repayment_data']);
            
            if ($data['again_platform_cycle'] == 0 && ($data['again_account_cycle'] != 0 || $data['again_pay_cycle'] != 0)) {
                $error[] = $v['id'];
                file_put_contents($log_file, $v['id']."\n",FILE_APPEND);
            } else {
                $ok[] =$v['id'];
            }
        }
        
        echo "<pre>";
        echo "ok<br/>";
        var_dump($ok);
        
        echo "<hr/>";
        
        echo "q<br/>";
        var_dump($error);
        
    }

    
    /**
     * 服务费转化为明细
     * @param float $rate   利率
     * @param float $cycle  周期
     * @return boolean | array
     * $cycle 1 需要特殊处理
     */
    public function ServerToDetail($rate, $cycle)
    {
        //周期为1天
        if ($cycle == 1) {
            $serverRateA = $rate;
            $serverRateB = $rate;
        } else {
            $serverRateA = abs(intval($rate/($cycle-1)));
            if (is_numeric($rate) && strpos($rate, '.')) {
                $rate = (float)$rate;
                $serverRateB = fmod($rate,($cycle-1));
            } else {
                $serverRateB = abs($rate%($cycle-1));
            }
        }
        
        $serverRateAs  = $this->getItem($serverRateA);
        $serverRateBs = $this->getItem($serverRateB);
        
        return [
            'platform'=>['platform_service' =>$serverRateAs['platform_service'],'platform_cycle'=>$cycle,'platform_cycle_rate'=>$serverRateBs['platform_service']],
            'account'=>['account_service' =>$serverRateAs['account_service'],'account_cycle'=>$cycle,'account_cycle_rate'=>$serverRateBs['account_service']],
            'pay'=>['pay_service' =>$serverRateAs['pay_service'],'pay_cycle'=>$cycle,'pay_cycle_rate'=>$serverRateBs['pay_service']]
        ];
    }
    
    /**
     * 明细换成整的服务费
     * @param array $service 全部的利息
     * @param array $cycle_rate 全部的变为利息
     * @param int $cycle 周期
     * @return boolean |array
     */
    public function DetailToServer($service, $cycle_rate, $cycle)
    {
        if (empty($service) || empty($cycle_rate)) {
            return false;
        }
        
        if ($cycle == 1) {
            $rate = $service['platform_service'] + $service['account_service'] + $service['pay_service'];
        } else {
            $serverRateAs = $service['platform_service'] + $service['account_service'] + $service['pay_service'];
            $serverRateBs = $cycle_rate['platform_cycle_rate'] + $cycle_rate['account_cycle_rate'] + $cycle_rate['pay_cycle_rate'];
            $rate = abs($serverRateAs * ($cycle-1)) + $serverRateBs;
        }
        
        return ['rate' => $rate, 'cycle' => $cycle];
    }
    
    /**
     * 计算各项费率
     * @param 费率 $serverRate
     */
    public function getItem($serverRate)
    {
        $is_float = false;
        
        if (is_numeric($serverRate) && strpos($serverRate, '.')) {
            $is_float = true;
            $_serverRate = explode(".",$serverRate);
            $serverRate = $_serverRate[0];
        }
        
        if ($serverRate == 1) {
            
            $ret = [
                'platform_service'  => 1,
                'account_service'   => 0,
                'pay_service'       => 0
            ];
        } else if($serverRate == 2){
            $ret = [
                'platform_service'  => 1,
                'account_service'   => 1,
                'pay_service'       => 0
            ];
        } elseif ($serverRate == 0) {
            $ret = [
                'platform_service'  => 0,
                'account_service'   => 0,
                'pay_service'       => 0
            ];
        } else {
            if (($serverRate+1)%3 === 0) {
                $num = ($serverRate+1)/3;
            } elseif(($serverRate-1)%3 === 0){
                $num = ($serverRate-1)/3;
            } else {
                $num = $serverRate/3;
            }
            
            $ret = [
                'platform_service'  => $num,
                'account_service'   => $num,
                'pay_service'       => $serverRate - (2*$num)
            ];
        }
        
        if ($is_float) {
            $ret['platform_service'] = (float)($ret['platform_service'].'.'.$_serverRate[1]);
        }
        
        return $ret;
    }
    
    /**
     * 兼容校验，反向检查
     * @param array $serve_free 标准明细
     * @param array $check 总的服务费
     * @return boolean
     */
    public function reverseCheck($serve_free, $check)
    {
        if (empty($serve_free) || empty($check)) {
            return false;
        }
        
        $server =[
            'platform_service' => $check['platform']['platform_service'],
            'account_service' => $check['account']['account_service'],
            'pay_service' => $check['pay']['pay_service']
        ];
        
        $cycle_rate =[
            'platform_cycle_rate' => $check['platform']['platform_cycle_rate'],
            'account_cycle_rate' => $check['account']['account_cycle_rate'],
            'pay_cycle_rate' => $check['pay']['pay_cycle_rate']
        ];
        
        $cycle = max([
            $check['platform']['platform_cycle'],
            $check['account']['account_cycle'],
            $check['pay']['pay_cycle']
        ]);
        
        $server_free = $this->DetailToServer($server, $cycle_rate, $cycle);
        
        if (intval(strval($server_free['rate']*1000)) != intval(strval($serve_free['server_rate']*1000)) || intval(strval($server_free['cycle']*1000)) != intval(strval($serve_free['server_cycle']*1000))) {
            return false;
        }
        
        return true;
    }
    
    /**
     * 检查提交的费率是否正确(严格检查)
     * @param array $serve_free 总的设置
     * @param array $check 各项设置
     * @return boolean
     */
    public function check($serve_free, $check)
    {
        if (empty($serve_free) || empty($check)) {
            return false;
        }
        
        if ($serve_free['server_rate'] == 0 && $serve_free['server_cycle'] == 0) {
            
            if ($check['platform']['platform_service'] == 0
                && $check['platform']['platform_cycle_rate'] == 0
                && $check['account']['account_service'] == 0
                && $check['account']['account_cycle_rate'] == 0
                && $check['pay']['pay_service'] == 0
                && $check['pay']['pay_cycle_rate'] == 0
                ) {
                    return true;
                }else {
                    return false;
                }
        }
        
        $res = $this->ServerToDetail($serve_free['server_rate'], $serve_free['server_cycle']);
        
        if ($check['platform']['platform_service'] != $res['platform']['platform_service']
            || $check['platform']['platform_cycle_rate'] != $res['platform']['platform_cycle_rate']
            || $check['account']['account_service'] != $res['account']['account_service']
            || $check['account']['account_cycle_rate'] != $res['account']['account_cycle_rate']
            || $check['pay']['pay_service'] != $res['pay']['pay_service']
            || $check['pay']['pay_cycle_rate'] != $res['pay']['pay_cycle_rate']
            ) {
                return false;
            }
            
            return true;
    }
    
    
}